import { useEffect, useState, useRef } from "react";

export function useAutoScrollList<T>(
  list: T[] = [],
  visibleCount: number = 4,
  itemHeight: number = 80,
  interval: number = 2000
) {
  //当前滚动第几条
  const [currentIndex, setCurrentIndex] = useState(0);
  //鼠标悬停是否停止
  const [isPaused, setIsPaused] = useState(false);
  //动画过渡
  const [transition, setTransition] = useState("transform 0.5s ease-in-out");
  //获取定时器，便于删除
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // 拼接一份数据，保证无缝循环
  const loopList = [...list, ...list];
  // console.log(timerRef);

  useEffect(() => {
    if (!list || list.length === 0) return;
    if (!isPaused) {
      timerRef.current = setInterval(() => {
        setCurrentIndex((prev) => {
          if (prev >= list.length) {
            setTransition("none");
            return 0;
          }
          setTransition("transform 0.5s ease-in-out");
          return prev + 1;
        });
      }, interval);
    }
    // useEffect可以返回一个函数，这个函数会在组件卸载或依赖项变化进行
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [list, interval, isPaused]);

  //留言容器高度
  const wrapperStyle: React.CSSProperties = {
    overflow: "hidden",
    height: `${visibleCount * itemHeight}px`,
  };

  const innerStyle: React.CSSProperties = {
    transform: `translateY(-${currentIndex * itemHeight}px)`,
    transition,
  };

  const onMouseEnter = () => setIsPaused(true);
  const onMouseLeave = () => setIsPaused(false);

  return {
    wrapperStyle,
    innerStyle,
    itemHeight,
    loopList,
    onMouseEnter,
    onMouseLeave,
  };
}
